package cn.iocoder.yudao.module.happycore.service;

import cn.iocoder.yudao.module.happycore.constants.DirectoryType;
import cn.iocoder.yudao.module.happycore.constants.ErrorCodeConstants;
import org.springframework.stereotype.Service;

import java.io.File;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.happycore.constants.ErrorCodeConstants.*;


@Service
public class ProjectFileService {

    /**
     * 创建项目
     * @param path
     */


    public String createFileInPath(String path) {
       //在当前目录创建文件
        String basePath = System.getProperty("user.dir")+"/happy-ox-projects";
        File folder = new File(basePath, path);
        if (!folder.exists()) {
            folder.mkdirs();
        }else {
            throw exception(PROJECT_HAS_EXIT);
        }
        return basePath+"/"+path;
    }

    /**
     * 创建子目录
     */
    public String createSubDirectory(String projectPath, String categoryName,Integer type) {
        File folder = new File(projectPath+"/"+DirectoryType.getPath(type), categoryName);

        if (!folder.exists()) {
            folder.mkdirs();
        }else {
            throw exception(OX_DIRECTORY_IS_EXISTS);
        }
        return projectPath+"/"+categoryName;
    }
    /**
     * 创建测试目录和训练目录
     */
    public void createTestAndTrain(String projectPath){
        File test = new File(projectPath+"/"+DirectoryType.getPath(DirectoryType.test));
        File train = new File(projectPath+"/"+DirectoryType.getPath(DirectoryType.train));
    }
    /**
     * 删除项目并且删除子目录
     *
     * @param projectPath 项目完整路径
     */
    public void deleteProject(String projectPath) {
        File projectDir = new File(projectPath);
        if (!projectDir.exists()) {
            throw exception(PROJECT_NOT_FOUND);
        }
        if (!deleteRecursively(projectDir)) {
            throw exception(ErrorCodeConstants.PROJECT_DELETE_FAILED);
        }
    }
    /**
     * 递归删除文件或目录
     *
     * @param file 要删除的文件或目录
     * @return 是否删除成功
     */
    private boolean deleteRecursively(File file) {
        if (file == null || !file.exists()) {
            return true;
        }
        if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null) {
                for (File child : children) {
                    if (!deleteRecursively(child)) {
                        return false;
                    }
                }
            }
        }
        return file.delete();
    }

    public boolean deleteModelFile(String modelPath){
        File modelFile = new File(modelPath);
        if (!modelFile.exists()) {
            throw exception(ErrorCodeConstants.MODEL_FILE_NOT_FOUND);
        }
        return modelFile.delete();
    }

}
